package net.organizer.ui.actionhandler;

import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;

import net.organizer.dao.Domain;
import net.organizer.dao.Org;
import net.organizer.ui.actionhandler.message.OptimisticConcurrencyConflictMessage;
import net.organizer.ui.actionhandler.message.UnknownEntityMessage;

import org.json.JSONObject;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.NotFoundException;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

public class OrgPutUpdateParentActionHandler extends ActionHandlerBase {
	private static final Logger logger = Logger.getLogger(OrgPutUpdateParentActionHandler.class.getName());
	
	@Override
	public void handleAction(HttpServletRequest req, JSONObject respJSONObject) throws Exception {
		logger.fine("handleAction");
		Objectify ofy = ObjectifyService.beginTransaction();
		long id = getParamValueAsLong(req, "id", true);
		logger.fine("handleAction... id: " + id);
		
		Domain domain = new Domain();
		domain.setName("domain1");
		try{
			Org org = ofy.get(Org.getKey(domain, id));
			Long version = getParamValueAsLong(req, "version", true);
			if(!org.getVersion().equals(version)){
				new OptimisticConcurrencyConflictMessage(id, respJSONObject);
				respJSONObject.put("org", org.toJSONObject());
				return;
			}
			org.setId(id);
			org.setDomainKey(domain.getKey());			
			Long parentOrgId = getParamValueAsLong(req, "parentOrgId", false);
			if(parentOrgId == null){
				org.setParentOrg(null);
			}else{
				Key<Org> parentOrgKey = Org.getKey(domain, getParamValueAsLong(req, "parentOrgId", true));
				Org parentOrg = ofy.get(parentOrgKey);
				org.setParentOrg(parentOrg); // also sets parentOrgKey
			}
			org.setVersion(version + 1);
			logger.fine(String.format("org after applying http params: %s", org));
			
			ofy.put(org); // figures out key from annotations?
			ofy.getTxn().commit();
			respJSONObject.put("org", org.toJSONObject());
		}catch(NotFoundException e){
			new UnknownEntityMessage(id, respJSONObject);
		}finally{
			if(ofy.getTxn().isActive()){
				ofy.getTxn().rollback();
			}
		}
	}
}
